# coding=utf-8
import os
import time
from selenium import webdriver

def alert():
    driver.execute_script("window.alert('这是一个alert弹框。');")
    time.sleep(2)
    #driver.switch_to_alert().accept()  #close the alert
    driver.switch_to_alert().dismiss()
def img():
    image=driver.find_element_by_tag_name("img")
    print(image.text)
    print(image.size)
    print(image.tag_name)

def href():
    for link in driver.find_elements_by_xpath("//*[@href]"):
        print(link.get_attribute("href"))

def screenshot():
    try:
        file_path = os.path.dirname(os.path.abspath('.')) + '/screenshots/'
        rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
        screen_name = file_path + rq + '.png'
        driver.get_screenshot_as_file(screen_name)
    except Exception as e:
        print(format(e))

if __name__ =='__main__':
    dir = os.path.dirname(os.path.abspath('.'))
    chrome_driver_path = dir + '/tools/chromedriver.exe'
    driver = webdriver.Chrome(chrome_driver_path)
    #driver.implicitly_wait(6)
    driver.get("https://www.baidu.com")
    #href()
    #screenshot()
    links = driver.find_elements_by_tag_name("a")
    #print("=============links",links)
    counts = len(links)
    '''
        for i in range(1,5):
        str_i = str(i)
        print('============i',i)
        driver.find_element_by_xpath("//*[@id='u1']/a["+str_i+"]").click()
        if i<5:
            driver.back()
    '''


    for n in range(2,5):
        str_n=str(n)
        print('=============n',n)
        driver.find_element_by_xpath("//*[@id='lh']/a["+str_n+"]").click()
        if n<5:
            driver.back()

